﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Newtonsoft.Json.Linq;
using System.Text;

namespace FloodFree.Phone
{
    public partial class LoginPage : PhoneApplicationPage
    {
        public LoginPage()
        {
            InitializeComponent();
            DataContext = App.LoginViewModel;
        }

        private void btLogin_Click(object sender, RoutedEventArgs e)
        {
            

            String username = tbUsername.Text;
            String password = tbPassword.Password;

            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            {
                MessageBox.Show("Informe o usuário e senha.");
                return;
            }

            string WS_URL = "http://floodfree.cloudapp.net/api/sessions/create";

            Uri uri = new Uri(WS_URL, UriKind.Absolute);
            WebClient client = new WebClient();

            client.UploadStringCompleted += (source, args) =>
            {
                if (args.Error != null)
                {
                    MessageBox.Show("Erro ao efetuar login.");
                    return;
                }

                JObject o = JObject.Parse(args.Result);
                int code = (int)o["Code"];

                if (code == -1)
                {
                    MessageBox.Show((string)o["Message"]);
                    return;
                }

                if (code == 1)
                {
                    App.LoginViewModel.Username = username;
                    App.LoginViewModel.Password = password;
                    MessageBox.Show("Login Efetuado com sucesso");
                    NavigationService.GoBack();
                }
            };

            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            StringBuilder postData = new StringBuilder();
            postData.Append("{\"username\":\"" + username + "\",");
            postData.Append("\"password\":\"" + password + "\"}");
            client.UploadStringAsync(uri, "POST", postData.ToString()); 

        }

        private void btCancelar_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }
    }
}